-- Filename: LingdiSweep.lua
-- Author: 2100
-- Date: 2024-10-16
-- Purpose: 后军领地扫荡
module("LingdiSweep" , package.seeall)

require "script/network/RequestCenter"
require "script/network/Network"
require "script/model/user/UserModel"
require "script/utils/TimeUtil"
require "script/ui/tip/AnimationTip"
require "script/utils/extern"
require "script/model/DataCache"
require "script/ui/houJun/lingDi/HJLingDiData"
require "script/ui/main/SweepAll"



local need_item_id = {} --填写示例：{0, 69048}-- 白名单，里面写要拉的物品id，多个id中间用英文逗号隔开
local dont_need_item_id = {} --填写示例：{60002, 69047}-- 黑名单，里面写不想要的物品id，多个id中间用英文逗号隔开
local rob_other_item = 1 -- 是否拉其他物品 0表示只拉need_item_id里面的，1表示除了dont_need_item_id里面的都要

--[[
物品id表
红矿石 69048
木材 69047
进阶丹 60002
神兵洗炼石 60025
阵旗强化令 60070
金币 0
装备进阶石 60036
真·进化石 60035
宝物晶石 60054
天命石 60051
金马精华 60065
金书精华 60066
赤金龙鳞石 60064
圣·进化石 60061
神器强化石 60080
神兵晶石 60068
阵旗精华 60078
红颜结 60114
圣·炼魂印 60071
圣·鬼谷子 60073
突破丹 60075
秘宝强化石 60085
神·进化石 64000
宝物金魂 60077
神兵金魂 60082
名将残卷 60090
化身突破石 60112
战车进阶石 60093
神·鬼谷子 60089
真神·进化石 68000
真神·鬼谷子 60099
圣神·进化石 68100
秘宝升星石 60087
红颜升星玉 60115
兵符白金魂 60100
]]--
--输出table信息
function printT(x)
    SweepAll.printTable1(x)
end

function prints(str)
    --SweepAll.prints(str)
end
--显示文字提示
function showTip(str)
    SweepAll.showTip(str)
end
--定时器函数
--node：节点，必填，一般为CCDirector:sharedDirector():getRunningScene()
--callback：调用函数，必填
--delay：延迟启动时间，单位秒，默认为0
--repeat_num：重复次数，默认为1次
function schedule(node, callback, delay, repeat_num)
    local run_num = repeat_num or 0
    if(run_num<=0)then
        run_num = 1
    end
    local delay = delay or 0
    if(delay<0)then
        delay=0
    end
    local actionArray = CCArray:create()
    local dely = CCDelayTime:create(delay)
    for i=1,run_num do
        actionArray:addObject(dely)
        actionArray:addObject(CCCallFunc:create(callback))
    end
    local seq = CCSequence:create(actionArray)
    node:runAction(seq)
    return seq
end

local houjun_index = 0
local houjun_index1 = 0
local lingdi_sweep_time = 0 --防止schedule(CCDirector:sharedDirector():getRunningScene(),lingdi_sweep,time)代码多次启动
local lingdi_rand_refresh_time = 0 -- 下次刷新敌人时间
local is_rand_refresh_schedule = 0 -- 防止schedule(CCDirector:sharedDirector():getRunningScene(),randUserInfo,time)代码多次启动
--后军扫荡
function lingdi_sweep_start()
    if(houjun_index~=0)then
        showTip("后军扫荡进行中")
        return
    end
    showTip("开启后军扫荡")
    if not DataCache.getSwitchNodeState(ksHouJunLingDi,false) then
        showTip("后军领地，等级未达到")
        return
    end
    houjun_index = houjun_index + 1
    houjun_getInfo()
end
function lingdi_sweep_stop()
    showTip("停止后军扫荡")
    houjun_index = 0
end
local my_items = {} -- 自己领地物品信息{track: {'drop_id': 10002,'item':1,'maxNum': 1,'name': 进阶丹}}
local other_items = {} -- 别人领地物品信息{server_id..pid: {'track':1,'drop_id': 10002, 'maxNum': 1,'name': 进阶丹,'server_id':12345678,'pid':12345678}}
local arr_hou_jun = {} -- 空闲后军列表 {{id:111,speed:111},{id:111,speed:111},...}
local transport_hou_jun = {} -- 运输后军列表 {{id:schedule},{id,schedule},...}schedule是否启动定时器0/1

function houjun_getInfo_callback(cbFlag,dictData,bRet)
    if dictData.err == "ok" then
        prints("houjun_getInfo_callback")
        local nowTime = TimeUtil.getSvrTimeByOffset()
        local info = dictData.ret
        local item_refresh_time = tonumber(info.item_refresh_time)
        local time = HJLingDiData.getNextItemRefreshTime(item_refresh_time) - nowTime
        local rTime = tonumber(info.rand_rfr_time) or 0
        local dbData = DB_Lingdi_game.getDataById(1)
        lingdi_rand_refresh_time = rTime + tonumber(dbData.free_refresh_random)
        is_rand_refresh_schedule = 0
        updateMyself(info.land_info)
        updateHouJun(info.hou_jun_info)
        if(lingdi_sweep_time<=nowTime)then
            prints("schedule lingdi_sweep "..time)
            schedule(CCDirector:sharedDirector():getRunningScene(),houjun_getInfo,time)
            lingdi_sweep_time = HJLingDiData.getNextItemRefreshTime(item_refresh_time)
            showTip("领地刷新剩余时间 "..TimeUtil.getTimeString(lingdi_sweep_time-nowTime).."\n刷新时间 "..TimeUtil.getTimeFormatAtDay(lingdi_sweep_time))
            prints("lingdi_sweep_time" .. TimeUtil.getTimeFormatYMDHMS(lingdi_sweep_time))
        end
        prints("schedule getTransInfo "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),getTransInfo,1)
    else
        printT(dictData.ret)
    end
end


function houjun_getInfo()
    if(houjun_index==0)then
        return
    end
    local args = Network.argsHandlerOfTable({ 1 })
    houjun_index = houjun_index + 1
    Network.no_loading_rpc(houjun_getInfo_callback, "houjun.getInfo" .. houjun_index, "houjun.getInfo", args, true)
end
function updateMyself(land_info)
    prints("updateMyself")
    my_items={}
    for k,v in pairs(land_info) do
        if(v.start_time==nil)then
            local itemData,itemLv,maxNum,dbData = HJLingDiData.getItemDataBy(v.drop_id, v.item)
            -- 自己领地内物品全要
            my_items[tostring(k)] = {["drop_id"]= v.drop_id, ["item"] = v.item,["maxNum"] = maxNum,["name"] = itemData[1].name}
        end
    end
end

function updateOther(info)
    prints("updateOther")
    other_items={}
    for a,b in pairs(info) do
        for k,v in pairs(b.land_info) do
            if(v.start_time==nil)then
                local itemData,itemLv,maxNum,dbData = HJLingDiData.getItemDataBy(v.drop_id, v.item)
                local isRob = false
                if(rob_other_item==0)then
                    isRob = false
                elseif(rob_other_item==1) then
                    isRob = true
                end
                for idx,id in pairs(need_item_id) do
                    if(tonumber(itemData[1].tid)==id)then 
                        isRob = true
                        break
                    end
                end
                for idx,id in pairs(dont_need_item_id) do
                    if(tonumber(itemData[1].tid)==id)then
                        isRob = false
                        break
                    end
                end
                if(isRob)then
                    table.insert(other_items, {["track"] = tostring(k),["drop_id"]= v.drop_id, ["item"] = v.item,["maxNum"] = maxNum,["name"] = itemData[1].name,["pos"] = v.pos,["server_id"] = b.server_id,["pid"]=b.pid})
                end
            end
        end
    end
    table.sort(other_items,function(a,b)
        return tonumber(a.pos) > tonumber(b.pos)
    end)
end

function updateHouJun(hou_jun_info)
    prints("updateHouJun")
    arr_hou_jun={}
    for k,v in pairs(hou_jun_info) do
        if(transport_hou_jun[v.id]==nil)then
            transport_hou_jun[v.id] = 0
        end
        if(v.track==nil)then
            local speed = HJLingDiData.getHJSpeedNumByLv(v.id,v.lv)
            table.insert(arr_hou_jun,{["id"]=v.id,["speed"]=speed})
            transport_hou_jun[v.id] = 0
        end
    end
    table.sort(arr_hou_jun,function(a,b)
        return tonumber(a.speed) > tonumber(b.speed)
    end)
end

function updateTransport(info)
    prints("updateTransport")
    printT(info)
    local nowTime = TimeUtil.getSvrTimeByOffset()
    for i=1,table.count(info) do
        local v = info[i]
        local time = v.time-nowTime
        if(time<0)then
            time=0
        end
        for m,n in pairs(v.me.arr_hou_jun) do
            if(transport_hou_jun[n.id]==0)then
                showTip("后军id："..n.id.."冷却时间："..time.." s")
                prints("schedule transport "..time)
                schedule(CCDirector:sharedDirector():getRunningScene(),getTransInfo,time)
                transport_hou_jun[n.id] = 1
            end
        end
    end
    printT(transport_hou_jun)
    prints("table.count(arr_hou_jun)="..table.count(arr_hou_jun))
    if(table.count(arr_hou_jun)~=0)then
        prints("schedule transport "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),transport,1)
    end
end
function getRandUserInfo_callback(cbFlag,dictData,bRet)
    if dictData.err == "ok" then
        prints("getRandUserInfo_callback")
        updateOther(dictData.ret)
        prints("schedule rob "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),rob,1)
    else
        printT(dictData.ret)
    end
end
function getRandUserInfo()
    if(houjun_index==0)then
        return
    end
    prints("getRandUserInfo")
    Network.no_loading_rpc(getRandUserInfo_callback, "houjun.getRandUserInfo", "houjun.getRandUserInfo", nil, true)
end

function getTransInfo_callback(cbFlag,dictData,bRet)
    if dictData.err == "ok" then
        prints("getTransInfo_callback")
        updateHouJun(dictData.ret.hou_jun_info)
        updateTransport(dictData.ret.info)
    else
        printT(dictData.ret)
    end
end
function getTransInfo()
    if(houjun_index==0)then
        return
    end
    prints("getTransInfo")
    houjun_index1 = houjun_index1 + 1
    Network.no_loading_rpc(getTransInfo_callback, "houjun.getTransInfo" .. houjun_index1, "houjun.getTransInfo", nil, true)
end
function randUserInfo_callback(cbFlag,dictData,bRet)
    if dictData.err == "ok" then
        prints("randUserInfo_callback")
        updateOther(dictData.ret)
        prints("schedule getTransInfo "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),houjun_getInfo,1)
    else
        printT(dictData.ret)
    end
end
function randUserInfo()
    if(houjun_index==0)then
        return
    end

    prints("randUserInfo")
    Network.no_loading_rpc(randUserInfo_callback, "houjun.randUserInfo", "houjun.randUserInfo", nil, true)
end
function rob_callback(cbFlag, dictData, bRet)
    if dictData.err == "ok" then
        prints("rob_callback")
        local info = dictData.ret
        updateHouJun(info.hou_jun_info)
        prints("schedule getTransInfo "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),getTransInfo,1)
    else
        printT(dictData.ret)
    end
end

function rob()
    if(houjun_index==0)then
        return
    end
    prints("rob")
    local houjunTab = {}
    local name = nil
    local track = nil
    local pServerId =nil
    local pPid = nil
    for k,v in pairs(other_items) do
        for m,n in pairs(arr_hou_jun) do
            table.insert(houjunTab,n.id)
            if(m==v.maxNum)then
                break
            end
        end
        track = v.track
        name = v.name
        pServerId = v.server_id
        pPid = v.pid
        break
    end
    if(track == nil)then
        local nowTime = TimeUtil.getSvrTimeByOffset()
        local time = lingdi_rand_refresh_time - nowTime
        if(time<0)then
            time = 0
        end
        if(is_rand_refresh_schedule == 0)then
            showTip("随机领地刷新时间"..TimeUtil.getTimeString(time))
            prints("schedule randUserInfo "..time)
            schedule(CCDirector:sharedDirector():getRunningScene(),randUserInfo,time)
            is_rand_refresh_schedule = 1
        end
        return
    end
    showTip("运输他人物品："..name)
    local args = Network.argsHandlerOfTable({ pServerId, pPid, track, houjunTab })
	Network.no_loading_rpc(rob_callback, "houjun.rob", "houjun.rob", args, true)
end
function transport_callback(cbFlag, dictData, bRet)
    if dictData.err == "ok" then
        prints("transport_callback")
        local info = dictData.ret
        updateHouJun(info.hou_jun_info)
        updateMyself(info.land_info)
        prints("schedule getTransInfo "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),getTransInfo,1)
        --updateTransport(info.info)
    else
        printT(dictData.ret)
    end
end
function transport()
    if(houjun_index==0)then
        return
    end
    prints("transport")
    local houjunTab = {}
    local name = nil
    local track = nil
    for k,v in pairs(my_items) do
        for m,n in pairs(arr_hou_jun) do
            table.insert(houjunTab,n.id)
            if(m==v.maxNum)then
                break
            end
        end
        track = k
        name = v.name
        break
    end
    if(track == nil)then
        showTip("领地无物品")
        prints("schedule getRandUserInfo "..1)
        schedule(CCDirector:sharedDirector():getRunningScene(),getRandUserInfo,1)
        return
    end
    showTip("运输领地物品："..name)
    local args = Network.argsHandlerOfTable({ track, houjunTab })
    Network.no_loading_rpc(transport_callback, "houjun.transport", "houjun.transport", args, true)
end
